import axios, { AxiosInstance } from "axios";
interface UploadParams {
    file: File;
    onProgress: (progress: number) => void;
}
class UploadService {
    private client: AxiosInstance;
    constructor() {
        this.client = axios.create({
            baseURL: "/predict",
            headers: {"Content-type": "application/json"}
        });
    }

    async get_base64(file:File) {
        return new Promise((resolve) =>{
            var reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onloadend  =  function () {
                var rawImg  = reader.result;
                if (rawImg == null){
                    resolve(null);
                    return
                }
               
                let imgBase64 = (<string>rawImg).split(',')[1];
                var data = {"images": [imgBase64]};
                
                console.log(data);
                resolve(data);
            };
        });
    }

    async uploadFile({ file, onProgress }: UploadParams) {
        console.log(file);
        // var reader = new FileReader()
        // let rawImg;
        // var data = {};
        // reader.readAsDataURL(file)
        // reader.onloadend  =  function () {
        //     rawImg = reader.result;
        //     let imgBase64 = rawImg.split(',')[1];
        //     data = {"images": [imgBase64]};
           
        //     console.log(data);
        // };
         
        
        return (await this.client.post("/chinese_ocr_db_crnn_server", await this.get_base64(file), 
        {
            onUploadProgress: (e: ProgressEvent) => {
                const percentCompleted = Math.round((e.loaded * 100) / e.total);
                onProgress(percentCompleted);
            },
        })).data;
    }
}

export default new UploadService();
